#!/bin/bash
# Copyright (c) 2020 maminjie <maminjie1@huawei.com>
# SPDX-License-Identifier: MulanPSL-2.0

name=maminjie
email="maminje1@huawei.com"
pyporter=~/openeuler/pyporter/pyporter

usage() {
    echo "Usage: pmt [GLOBALOPTS] SUBCOMMAND [OPTS] [ARGS...]"
    echo "or: pmt help SUBCOMMAND"
    echo ""
    echo "package management tools."
    echo "Type 'pmt help <subcommand>' for help on a specific subcommand."
    echo ""
    echo "Commands:"
    echo "      specprep (sp)       Prepare the spec file" 
    echo "      pypkgprep (pyp)     Prepare python package"
    echo "      help (?, h)         Give detailed help on a specific sub-command"
    echo ""
    echo "Global Options:"
    echo "      -h, --help          Show this help message and exit"
    echo ""
}

usage_specprep() {
    echo "specprep (sp): Prepare the spec file"
    echo ""
    echo "usage:"
    echo "      pmt sp SPEC"
    echo ""
}

usage_pypkgprep() {
    echo "pypkgprep (pyp): Prepare python package"
    echo ""
    echo "usgae:"
    echo "      pmt pyp MODULE"
    echo ""
    echo "example:"
    echo "      mkdir python-module"
    echo "      cd python-module"
    echo "      pmt pyp module"
    echo ""
}

single_merge() {
    awk -v key="$1" -v max_len=80 -F : '
    BEGIN {
        tmp="";
    }
    {
        if (key == $1) {
            if (NF > 2) {
                oofs=FS;FS="#";
                bbb=sub(/[[:alnum:]]+:/,"",$0);
                aaa=$bbb;
                FS=oofs;
            } else {
                $1="";
                aaa=$0;
            }

            tmp1=tmp aaa
            gsub(" +"," ",tmp1);
            #print FNR tmp1
            if (length(tmp1) > max_len) {
                gsub(" +"," ",tmp);
                printf "%-20s%s\n",key ":",tmp;
                tmp="";
            }
            tmp=tmp aaa;
        } else {
            if (length(tmp) != 0) {
                gsub(" +"," ",tmp);
                printf "%-20s%s\n",key ":",tmp;
                tmp="";
            }
            print $0;
        }
    }'
}

header_align() {
    awk '{
        if ($0 ~ /^[A-Z][[:alnum:]]*: /) {
            va="";
            for(i=2;i<=NF;i++) {va=va" "$i};
            printf("%-20s%s\n",$1,va);
        } else {
            print $0;
        }
    }'
}

do_specprep() {
    if [ $# != 1 ]; then
        usage_specprep; exit
    fi
    
    file_o=$1
    file=${file_o}.cp
    cp -f $file_o $file

    # got verison release
    version=$(cat $file | grep '^Version' | awk '{print $2}')
    release_oo=$(cat $file | grep '^Release' | awk '{print $2}')
    #release_o=`echo $release_oo | sed 's/%{.*}//'`
    #release=$((release_o+1))
    release=1
    
    # convert tab
    sed -i 's/\t/    /g' $file
    # delete comment
    sed -i '/^#.*/d' $file

    # changelog replace
    sed -i '/^%changelog/,$d' $file
    date=$(date +"%a %b %_d %Y")
    changelog="%changelog\n* $date $name <$email> - $version-$release\n- package init"
    echo -e $changelog >> $file

    # change release
    sed -i "/^Release.*$/s/${release_oo}/${release}/" $file
    # delete Group Tags
    sed -i '/^Group.*/d' $file

    # header align
    cat $file | header_align > .$file
    mv .$file $file
    # headers merge
    cat $file | single_merge "BuildRequires" | single_merge "Requires" > .$file
    mv .$file $file

    # insert enter
    sed -i '/^$/d' $file
    sed -i '/^%package.*/i\ ' $file
    sed -i '/^%pre.*/i\ ' $file
    sed -i '/^%post.*/i\ ' $file
    sed -i '/^%build.*/i\ ' $file
    sed -i '/^%install.*/i\ ' $file
    sed -i '/^%check*/i\ ' $file
    sed -i '/^%files.*/i\ ' $file
    sed -i '/^%changelog.*/i\ ' $file

    # delete blank
    sed -i 's/[[:blank:]]\{1,\}$//g' $file

    mv -b -f $file $file_o
}

do_pypkgprep() {
    if [ $# != 1 ]; then
        usage_pypkgprep; exit
    fi
    module=$1
    package=$(basename $(pwd))

    if [ ! -f "$pyporter" ]; then
        echo "please prepare the pyporter firstly"
        exit
    fi

    if [ -z "$package" ]; then
        echo "the package is invalid"
        exit
    fi

    # download tarball
    $pyporter $module -d

    # create spec
    spec=$package.spec
    $pyporter $module -s -o $spec

    # update changelog
    if [ -f "$spec" ]; then
        version=$(cat $spec | grep '^Version' | awk '{print $2}')
        release=1
        sed -i -e "s/Python_Bot <Python_Bot@openeuler.org>/$name <$email> - $version-$release/" \
            -e 's/Package Spec generated/package init/' $spec
    fi
}

do_help() {
    case $1 in
        "specprep"|"sp") 
            usage_specprep
            ;;
        "pypkgprep"|"pyp") 
            usage_pypkgprep
            ;;
        *)
            usage
            ;;
    esac
}

main() {
    local subcmd=$1
    
    if [ $# -gt 0 ]; then
        shift
    fi

    case $subcmd in
        "specprep"|"sp")
            do_specprep "$@"
            ;;
        "pypkgprep"|"pyp")
            do_pypkgprep "$@"
            ;;
        "help"|"?"|"h")
            do_help "$@"
            ;;
        *)
            usage
            ;;
    esac
}

main "$@"

